package com.android.common.permission;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.android.common.permission.callback.OnPermissionCallBack;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by navychen on 16/8/2.
 */
public class PermissonHelper  implements  ActivityCompat.OnRequestPermissionsResultCallback {

    private String TAG = PermissonHelper.class.getSimpleName();


    private static PermissonHelper instance;


    private OnPermissionCallBack onPermissionCallBack;
    private Activity activity;


    private boolean isDebug = false;

    public PermissonHelper(Activity activity) {
        this.activity = activity;
        if (activity instanceof OnPermissionCallBack) {
            this.onPermissionCallBack =(OnPermissionCallBack) activity;
        } else {
            throw new IllegalArgumentException(activity.getClass().getSimpleName()+" 必须实现 OnPermissionCallBack 借口");
        }
    }

    public PermissonHelper(Activity activity, OnPermissionCallBack onPermissionCallBack) {
        this.activity = activity;
        this.onPermissionCallBack = onPermissionCallBack;
    }



    public void requestPermissions(@NonNull String[] permissionName , int requestCode){
        if (isDebug) {
            Log.d(TAG, "requestPermissions is calll "+  permissionName);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //只有当版本大于等于23才进行权限处理
            //开始处理权限
            handlePermissions(permissionName, requestCode);
        } else {
            /**
             * 理论上,当版本小于23时,直接调用onPermissionGranted方法即可,
             * 但是会出现 当用户在设置中,将权限关闭,出现bug
             * 所以添加了 权限检查
             */
            if (checkSelfPermissions(permissionName)) {
                onPermissionCallBack.onPermissionGranted(permissionName, requestCode);
            } else {
                onPermissionCallBack.onPermissionReject(permissionName, requestCode);
            }
        }
    }


    public void setIsDebug(boolean isDebug) {
        this.isDebug = isDebug;
    }




    public boolean checkSelfPermissions(String[] permissionName){
        if (isDebug) {
            Log.d(TAG, "checkSelfPermission");
        }
        for (String permission : permissionName) {
            if (ActivityCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    private void handlePermissions(String[] permissionName, int requestCode){
        String[] permissions = needHandlePermissons(permissionName);
        if (permissions.length == 0) {
            onPermissionCallBack.onPermissionGranted(permissionName, requestCode);
            return;
        }
        //检验权限是否合法
        for (String permisson: permissionName) {
            if (!permissionExists(permisson, requestCode)){
                Log.d(TAG, permisson+"发生错误");
                return;
            } else {
               if(ActivityCompat.shouldShowRequestPermissionRationale(activity, permisson)) {
                   onPermissionCallBack.onPermissionNeedExplanation(permisson, requestCode);
               }
            }
        }

        ActivityCompat.requestPermissions(activity, permissions, requestCode);
    }


    /**
     * 确定需要声请的权限
     */
    private String[] needHandlePermissons(String[] permissionName){
        ArrayList<String> needPermissons = new ArrayList<>();
        for (String permission: permissionName){
            if (ActivityCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                needPermissons.add(permission);
            }
        }
        return needPermissons.toArray(new String[needPermissons.size()]);
    }



    /**
     *判断 权限是否在AndroidManifest.xml声请
     */
    public boolean permissionExists(@NonNull String permissionName, int requestCode) {
        try {
            PackageInfo packageInfo = activity.getPackageManager().getPackageInfo(activity.getPackageName(), PackageManager.GET_PERMISSIONS);
            if (packageInfo.requestedPermissions != null) {
                for (String p : packageInfo.requestedPermissions) {
                    if (p.equals(permissionName)) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            onPermissionCallBack.onPermissionError(permissionName, requestCode, e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 验证权限
     * @param grantResults
     * @return
     */
    public boolean verifyPermissions(int[] grantResults) {
        // At least one result must be checked.
        if(grantResults.length < 1){
            return false;
        }

        // Verify that each required permission has been granted, otherwise return false.
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    }
}
